package com.cj.sbs.service.impl;

import com.cj.sbs.base.ReturnCodeEnum;
import com.cj.sbs.base.exception.SbsException;
import com.cj.sbs.data.TokenData;
import com.cj.sbs.mapper.UserMapper;
import com.cj.sbs.mapper.UserPermissionsMapper;
import com.cj.sbs.mapper.UserRolesMapper;
import com.cj.sbs.param.LoginParam;
import com.cj.sbs.po.User;
import com.cj.sbs.service.UserService;
import com.cj.sbs.util.JWTUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName: UserServiceImpl <br/>
 * Function: user service impl <br/>
 * date: 2018/04/24 17:09 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRolesMapper userRolesMapper;
    @Resource
    private UserPermissionsMapper userPermissionsMapper;

    @Override
    public User selectByUserName(String userName) {
        return userMapper.selectByUserName(userName);
    }

    @Override
    public List<String> queryRolesByUserName(String userName) {
        return userRolesMapper.queryRolesByUserName(userName);
    }

    @Override
    public List<String> queryPermissionsByUserName(String userName) {
        return userPermissionsMapper.queryPermissionsByUserName(userName);
    }

    @Override
    public TokenData login(LoginParam loginParam) {
        User user = userMapper.selectByUserName(loginParam.getUsername());
        if (user == null) {
            throw new SbsException(ReturnCodeEnum.USER_ACOUNT_ERROR);
        }
        Md5Hash md5Hash = new Md5Hash(loginParam.getPassword(), loginParam.getUsername());
        if (!md5Hash.toString().equals(user.getPassword())) {
            throw new SbsException(ReturnCodeEnum.USER_ACOUNT_ERROR);
        }
        String token = JWTUtil.sign(user.getUsername(), user.getPassword());
        return new TokenData(token);
    }
}
